﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IPC.Communication.Core.IMessage
{
    public class ModbusTcpMessage : INetMessage
    {
        public int ProtocolHeadBytesLength
        {
            get
            {
                return 8;
            }
        }

        public byte[] HeadBytes
        {
            get;
            set;
        }

        public byte[] ContentBytes
        {
            get;
            set;
        }

        public byte[] SendBytes
        {
            get;
            set;
        }

        public bool IsCheckMessageId
        {
            get;
            set;
        }

        public int GetContentLengthByHeadBytes()
        {
            byte[] expr_07 = this.HeadBytes;
            int? num = (expr_07 != null) ? new int?(expr_07.Length) : null;
            int protocolHeadBytesLength = this.ProtocolHeadBytesLength;
            bool flag = num.GetValueOrDefault() >= protocolHeadBytesLength & num.HasValue;
            int result;
            if (flag)
            {
                int num2 = (int)this.HeadBytes[4] * 256 + (int)this.HeadBytes[5];
                bool flag2 = num2 == 0;
                if (flag2)
                {
                    byte[] array = new byte[this.ProtocolHeadBytesLength - 1];
                    for (int i = 0; i < array.Length; i++)
                    {
                        array[i] = this.HeadBytes[i + 1];
                    }
                    this.HeadBytes = array;
                    result = (int)this.HeadBytes[5] * 256 + (int)this.HeadBytes[6] - 1;
                }
                else
                {
                    result = num2 - 2;
                }
            }
            else
            {
                result = 0;
            }
            return result;
        }

        public bool CheckHeadBytesLegal(byte[] token)
        {
            bool isCheckMessageId = this.IsCheckMessageId;
            bool result;
            if (isCheckMessageId)
            {
                bool flag = this.HeadBytes == null;
                if (flag)
                {
                    result = false;
                }
                else
                {
                    bool flag2 = this.SendBytes[0] != this.HeadBytes[0] || this.SendBytes[1] != this.HeadBytes[1];
                    result = (!flag2 && this.HeadBytes[2] == 0 && this.HeadBytes[3] == 0);
                }
            }
            else
            {
                result = true;
            }
            return result;
        }

        public int GetHeadBytesIdentity()
        {
            return (int)this.HeadBytes[0] * 256 + (int)this.HeadBytes[1];
        }

        public ModbusTcpMessage()
		{
			this.IsCheckMessageId = true;
		}
    }
}
